package com.sishu.njrtsdms.controller;

import com.sishu.njrtsdms.domain.core.Groups;
import com.sishu.njrtsdms.domain.core.PageInfo;
import com.sishu.njrtsdms.domain.core.R;
import com.sishu.njrtsdms.domain.dto.UserDTO;
import com.sishu.njrtsdms.domain.vo.UserVO;
import com.sishu.njrtsdms.service.UserService;

import org.jooq.types.ULong;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/user")
@Slf4j
@Validated
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/page")
    public R<PageInfo<UserVO>> pageUser(UserDTO userDTO) {
        var userVOPageInfo = userService.page(userDTO);
        return R.ok(userVOPageInfo);
    }

    /**
     * 条件精确查询用户总数
     *
     * @param userDTO 用户查询条件
     * @return 用户符合条件的总数
     */
    @GetMapping("/totalCount")
    public R<Long> TeachingConstructionProjectTotalCount(UserDTO userDTO) {
        Long userVOTotalCount = userService.totalCount(userDTO);
        return R.ok(userVOTotalCount);
    }

    @GetMapping("/{userId}")
    public R<UserVO> getUser(@PathVariable(required = false, name = "userId")
                             ULong userId) {
        UserVO userVO = userService.queryOneUserByUserId(userId);
        return R.ok(userVO);
    }

    @PostMapping
    public R<String> saveUser(@Validated({Groups.Add.class})
                              @RequestBody
                              UserDTO userDTO) {
        userService.addUser(userDTO);
        return R.ok();
    }


    @PutMapping("/{userId}")
    public R<String> updateUser(@PathVariable(name = "userId")
                                ULong userId,
                                @Validated({Groups.Update.class})
                                @RequestBody
                                UserDTO userDTO) {
        userService.updateUser(userId, userDTO);
        return R.ok();
    }

    /**
     * 删除用户
     *
     * @param userId 用户id
     */
    @DeleteMapping("/{userId}")
    public R<String> deleteUser(@PathVariable(name = "userId")
                                ULong userId) {
        userService.deleteUser(userId);
        return R.ok();
    }

}
